package com.sicheng.algorithm.string;

import java.util.Objects;

import static com.sicheng.algorithm.string.LeftRotateString.reverse;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/9/18 14:32
 */
public class ReverseSentence {
    public static void main(String[] args) {

        String sentence = new ReverseSentence().reverseSentence("I am a students.");
        System.out.println(sentence);

    }

    /**
     * 翻转单词顺序列
     * Input:
     * "I am a student."
     * <p>
     * Output:
     * "student. a am I"
     */
    public String reverseSentence(String sentence) {
        if (Objects.isNull(sentence) || sentence.length() == 0)
            return null;

        char[] chars = sentence.toCharArray();
        int i = 0, j = 0;

        while (i < sentence.length() && j < sentence.length()) {
            while (j < sentence.length() && chars[j] != ' ')
                j++;

            if (i < j - 1)
                reverse(chars, i, j - 1);
            i = j;

            while (i < sentence.length() && j < sentence.length() && chars[j] == ' ') {
                i++;
                j++;
            }
        }
        reverse(chars, 0, chars.length - 1);
        return String.valueOf(chars);
    }
}
